package com.always.electrical.energy.web.log;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class AccessLog {
    private static final String BR = System.lineSeparator();
    private static final String LOG = "[访问记录]：{} # {}{}" + BR + "[返回数据]：{}";
    private static final String ERROR_LOG = "[访问记录]：{} # {},{}" + BR + "[抛出异常]：{}";

    @Pointcut("execution(public * com.always.electrical.energy.web..controller.*.*(..)) ")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        Object returnVal;
        try {
            returnVal = point.proceed();
            if (returnVal instanceof DeferredResult) {
                DeferredResult<?> deferredResult = (DeferredResult<?>) returnVal;
                deferredResult.onCompletion(() -> log.info(LOG,
                        point.getTarget().getClass().getSimpleName(),
                        point.getSignature().getName(),
                        point.getArgs().length > 0 ? (BR + "[传递参数]：" + Arrays.toString(point.getArgs())) : "",
                        deferredResult.getResult() != null ? deferredResult.getResult().toString() : deferredResult));
            } else {
                log.info(LOG,
                        point.getTarget().getClass().getSimpleName(),
                        point.getSignature().getName(),
                        point.getArgs().length > 0 ? (BR + "[传递参数]：" + Arrays.toString(point.getArgs())) : "",
                        returnVal);
            }
        } catch (Throwable throwable) {
            log.error(ERROR_LOG,
                    point.getTarget().getClass().getSimpleName(),
                    point.getSignature().getName(),
                    point.getArgs().length > 0 ? (BR + "[传递参数]：" + Arrays.toString(point.getArgs())) : "",
                    throwable.getMessage());
            throw throwable;
        }
        return returnVal;
    }
}
